package com.inter.controller.newoutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DevicePackageCoverPicture;
import com.inter.entity.common.DevicePackageMarketingStrategy;
import com.inter.entity.common.PartnerProductPackage;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.listofpackages.request.RequestListOfPackages;
import com.inter.entity.newinterentity.listofpackages.request.RequestListOfPackagesData;
import com.inter.entity.newinterentity.listofpackages.response.ResponseListOfPackages;
import com.inter.entity.newinterentity.listofpackages.response.ResponseListOfPackagesData;
import com.inter.entity.newinterentity.listofpackages.response.ResponseListOfPackagesTradeData;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 线上套餐列表
 *
 * @author lm
 * @date 2018/12/20
 */
@RestController
@Api(description = "获取上线套餐列表")
public class OnlineListController {
    private static Logger logger = Logger.getLogger(OnlineListController.class);
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    @CrossOrigin
    @RequestMapping(value = "onlineList", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取套餐列表", response = ResponseListOfPackages.class)
    public String onlineListOfPackages(@ApiParam @RequestBody RequestListOfPackages requestListOfPackages) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        String requestStr = JSON.toJSONString(requestListOfPackages);

        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestListOfPackages requestPackage = JSONArray.parseObject(requestStr, RequestListOfPackages.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestListOfPackagesData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String currencyCodeType = requestData.getCurrencyCodeType();
                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang) || StringUtils.isBlank(currencyCodeType)) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        logger.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            logger.info("签名验证失败！");
                            jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                            return jsonString;
                        } else {
                            //签名验证通过
                            List<PartnerProductPackage> partnerProductPackageList = partnerProductPackageService.getProductListByPartnerCode(partnerCode);
                            if (partnerProductPackageList == null || partnerProductPackageList.size() <= 0) {
                                //如果没有取到相应的值，也要个前端回复一个公众的报文
                                logger.info("当前渠道无上线套餐！");
                                jsonString = utils.requestCannotRespondMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                String packageType = null;
                                String packageCode = null;
                                String pachageName = null;
                                String pachageNameEN = null;

                                String priceType = null;
                                String packageFlow = null;
                                String buyType = null;
                                String minOrderPeriod = null;
                                String maxOrderPeriod = null;
                                String coverCountryMcc = null;
                                String coverCountrys = null;
                                String coverCountrysEN = null;

                                String pictureIndex = null;
                                String pictureDetails = null;
                                String packageImgDesc = null;
                                String packageImgDescEN = null;


                                String countryNameIndex = null;
                                String countryNameIndexEN = null;
                                String countryNameDetails = null;
                                String countryNameDetailsEN = null;
                                String packageTextDesc = null;
                                String packageTextDescEN = null;
                                String packageDetailsDesc = null;
                                String packageDetailsDescEN = null;
                                String packageDetailsAdd = null;
                                String packageDetailsAddEN = null;

                                String strategyCode = null;
                                String salePriceCNY = null;
                                String salePriceUSD = null;
                                String strategyDescCNY = null;
                                String strategyDescUSD = null;

                                List<ResponseListOfPackagesTradeData> responseTradeData = new ArrayList<ResponseListOfPackagesTradeData>();
                                ResponseListOfPackagesTradeData tra = null;
                                //到这边说明是有上线套餐

                                for (PartnerProductPackage product : partnerProductPackageList) {
                                    packageType = product.getPackageType();
                                    packageCode = product.getPackageCode();
                                    pachageName = product.getPackageName();
                                    pachageNameEN = product.getPackageNameEN();
                                    priceType = product.getPriceType();
                                    packageFlow = product.getPackageFlow();
                                    buyType = product.getBuyType();
                                    minOrderPeriod = product.getMinOrderPeriod();
                                    maxOrderPeriod = product.getMaxOrderPeriod();
                                    coverCountryMcc = product.getCoverCountryMcc();
                                    coverCountrys = product.getCoverCountrys();
                                    coverCountrysEN = product.getCoverCountrysEN();

                                    // 1,从CoverPicture表中把图片信息取出来 ,packageCode,partnerCode
                                    List<DevicePackageCoverPicture> pictureList = partnerProductPackageService.getPictureByPartnerCodeAndPackageCode(packageCode, partnerCode);
                                    for (DevicePackageCoverPicture covers : pictureList) {
                                        pictureIndex = covers.getPictureIndex();
                                        pictureDetails = covers.getPictureDetails();
                                        packageImgDesc = covers.getPackageImgDesc();
                                        packageImgDescEN = covers.getPackageImgDescEN();

                                        countryNameIndex = covers.getCountryNameIndex();
                                        countryNameIndexEN = covers.getCountryNameIndexEN();
                                        countryNameDetails = covers.getCountryNameDetails();
                                        countryNameDetailsEN = covers.getCountryNameDetailsEN();
                                        packageTextDesc = covers.getPackageTextDesc();
                                        packageTextDescEN = covers.getPackageTextDescEN();
                                        packageDetailsDesc = covers.getPackageDetailsDesc();
                                        packageDetailsDescEN = covers.getPackageDetailsDescEN();
                                        packageDetailsAdd = covers.getPackageDetailsAdd();
                                        packageDetailsAddEN = covers.getPackageDetailsAddEN();
                                    }

                                    // 2,从PackageMarketingStrategy表中把营销信息取出来 ,partnerCode
                                    List<DevicePackageMarketingStrategy> strategyList = partnerProductPackageService.getStrategyByPartnerCodeAndPackageCode(packageCode, partnerCode);
                                    for (DevicePackageMarketingStrategy strategy : strategyList) {

                                        strategyDescCNY = strategy.getStrategyDescCNY();
                                        strategyDescUSD = strategy.getStrategyDescUSD();
                                        salePriceCNY = strategy.getSalePriceCNY();
                                        salePriceUSD = strategy.getSalePriceUSD();
                                        strategyCode = strategy.getStrategyCode();

                                    }
                                    //开始拼接tradeData
                                    tra = new ResponseListOfPackagesTradeData();
                                    tra.setPackageType(packageType);
                                    tra.setPackageCode(packageCode);
                                    if ("en".equals(lang)) {
                                        tra.setPackageName(pachageNameEN);
                                    } else {
                                        tra.setPackageName(pachageName);
                                    }

                                    tra.setPriceType(priceType);
                                    tra.setPackageFlow(packageFlow);
                                    tra.setBuyType(buyType);
                                    tra.setMinOrderPeriod(minOrderPeriod);
                                    tra.setMaxOrderPeriod(maxOrderPeriod);
                                    //价格回调方案
                                    if (currencyCodeType.equalsIgnoreCase("CNY")) {
                                        if ("1".equals(strategyCode)) {
                                            //热销，就是正常价格
                                            tra.setSalePriceCNY(salePriceCNY);
                                            tra.setSalePriceUSD(salePriceUSD);
                                        } else {
                                            //特价
                                            tra.setSalePriceCNY(strategyDescCNY);
                                            tra.setSalePriceUSD(strategyDescUSD);
                                        }
                                    } else if (currencyCodeType.equalsIgnoreCase("USD")) {

                                        if ("1".equals(strategyCode)) {
                                            //热销，就是正常价格
                                            tra.setSalePriceCNY(salePriceCNY);
                                            tra.setSalePriceUSD(salePriceUSD);
                                        } else {
                                            //特价
                                            tra.setSalePriceCNY(strategyDescCNY);
                                            tra.setSalePriceUSD(strategyDescUSD);
                                        }
                                    }

                                    tra.setMcc(coverCountryMcc);
                                    tra.setPictureIndex(pictureIndex);
                                    tra.setPictureDetails(pictureDetails);
                                    //中英文版方案：
                                    if ("en".equals(lang)) {
                                        tra.setPackageImgDesc(packageImgDescEN);
                                        tra.setCountryName(coverCountrysEN);
                                        tra.setCountryNameIndex(countryNameIndexEN);
                                        tra.setCountryNameDetails(countryNameDetailsEN);
                                        tra.setPackageTextDesc(packageTextDescEN);
                                        tra.setPackageDetailsDesc(packageDetailsDescEN);
                                        tra.setPackageDetailsAdd(packageDetailsAddEN);
                                    } else {
                                        tra.setPackageImgDesc(packageImgDesc);
                                        tra.setCountryName(coverCountrys);
                                        tra.setCountryNameIndex(countryNameIndex);
                                        tra.setCountryNameDetails(countryNameDetails);
                                        tra.setPackageTextDesc(packageTextDesc);
                                        tra.setPackageDetailsDesc(packageDetailsDesc);
                                        tra.setPackageDetailsAdd(packageDetailsAdd);
                                    }

                                    responseTradeData.add(tra);

                                }

                                //循环结束开始拼接data
                                ResponseListOfPackagesData data = new ResponseListOfPackagesData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeTime(curtime);
                                data.setTradeType(tradeType);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(responseTradeData);
                                //赋值ResponsePackageHome
                                ResponseListOfPackages home = new ResponseListOfPackages();
                                home.setData(data);
                                home.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(home);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;

                            }

                        }
                    }
                }
            }
        }
    }
}

